package com.yuhf.db.utils;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class DBUtils {
	
	private static Logger log=Logger.getLogger(DBUtils.class);
    
    public static String printRealSql(String sql, Object[] params) {
    	if(params == null || params.length == 0) {
    		log.info("The SQL is------------>\n" + sql);
    		return sql;
    	}
    	
    	if (!match(sql, params)) {
    		log.info("SQL 语句中的占位符与参数个数不匹配。SQL：" + sql);
    		return null;
    	}
     
    	int cols = params.length;
    	Object[] values = new Object[cols];
    	System.arraycopy(params, 0, values, 0, cols);
     
    	for (int i = 0; i < cols; i++) {
    		Object value = values[i];
    		if (value instanceof Date) {
    			values[i] = "'" + value + "'";
    		} else if (value instanceof String) {
    			values[i] = "'" + value + "'";
    		} else if (value instanceof Boolean) {
    			values[i] = (Boolean) value ? 1 : 0;
    		}
    	}
    	
    	String statement = String.format(sql.replaceAll("\\?", "%s"), values);
    	log.info("The SQL is------------>\n" + statement);
     
    	//ConnectionMgr.addSql(statement); // 用来保存日志
    	
    	return statement;
    }
     
    private static boolean match(String sql, Object[] params) {
    	if(params == null || params.length == 0) return true; // 没有参数，完整输出
    	
    	Matcher m = Pattern.compile("(\\?)").matcher(sql);
    	int count = 0;
    	while (m.find()) {
    		count++;
    	}
    	
    	return count == params.length;
    }
}
